#!env python
# -*- encoding: utf-8 -*-
import urllib2
import urllib
import time
from dbhelper import DbHelper



#curl 'http://www.mytalkbox.com/talkbox/api/profile?action=getProfile' 
# -d 'token=pQd6FjuK7Px2bIJdQQE6FOl5u5svEVn8&tbId=1&clientType=1' 
# -H 'User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)'


token='token=NQteFAdgIYA7tuW6wrviboQAiu4fFVYE&clientType=1'
Tstdb=None
headers={
    "Content-Type": "application/x-www-form-urlencoded",
    "User-Agent": "Apache-HttpClient/UNAVAILABLE (java 1.4)"
}

def getProfile(id):
    url='http://www.mytalkbox.com/talkbox/api/profile?action=getProfile'
    post_data = "tbId=%d&%s" % (id, token)
    
    while True:
        try:
            req=urllib2.Request(url, post_data, headers)
            r = urllib2.urlopen(req)
            content = r.read()
            print("%d:%s" %(id ,content))
        except Exception, e:
            print(e)
        else:
            break
    return content


def search(email):
    url='http://www.mytalkbox.com/talkbox/api/user?action=searchInfo'
    email=urllib.quote(email.encode('utf8')) 
    post_data = 'email=%s&%s' % (email, token)

    while True:
        try:
            req=urllib2.Request(url, post_data, headers)
            r = urllib2.urlopen(req)
            content = r.read()
            print("%s:%s" %(email ,content))
        except Exception, e:
            print(e)
        else:
            break
    return content


def docrawl():
    global Tstdb
    id = 1055
    while (id < 0xffffffff):
        print 'The id is:', id
        content = getProfile(id)
        Tstdb.insertALine(id, content)
        id = id + 1
        time.sleep(0.5)



if __name__ == "__main__":
    global Tstdb
    Tstdb = DbHelper('talkbox.db')
    docrawl()

